package com.zll.exception;

import com.zll.enums.GlobalEnumException;
import com.zll.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult handle(Exception e) {
        log.error("全局异常，Exception异常信息为：{}",e.getMessage());
        e.printStackTrace();
        return JSONResult.error(GlobalEnumException.NO);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult handle(GlobalCustomException e) {
        log.error("自定义异常，GlobalExceptionHandler异常信息为：{}",e.getMessage());
        e.printStackTrace();
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult handle(MethodArgumentNotValidException e) {
        log.error("校验异常，MethodArgumentNotValidException异常信息为：{}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        final StringBuffer sb = new StringBuffer();
        allErrors.forEach(obj->{
           String defaultMessage = obj.getDefaultMessage();
           sb.append(defaultMessage+"||");
        });
        return JSONResult.error(sb.toString(),"-2");
    }





}
